'use client';

import { useState } from 'react';
import { Form, Input, Button, Card, Typography, Space, Message } from '@arco-design/web-react';
import { IconUser, IconLock } from '@arco-design/web-react/icon';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import Link from 'next/link';

const FormItem = Form.Item;
const { Title, Text } = Typography;

export default function LoginPage() {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const { login } = useAuth();

  const handleSubmit = async (values: { username: string; password: string }) => {
    setLoading(true);
    try {
      console.log('开始提交登录表单...');
      const success = await login(values.username, values.password, 'customer');
      console.log('登录结果:', success);

      if (success) {
        console.log('登录成功，准备跳转...');
        router.push('/');
        console.log('跳转指令已发送');
      } else {
        console.log('登录失败，不进行跳转');
      }
    } catch (error) {
      console.error('登录过程中发生错误:', error);
      // Message.error('登录过程中发生错误');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex justify-center items-center min-h-[80vh]">
      <Card className="w-full max-w-md shadow-md">
        <div className="text-center mb-6">
          <Title heading={3}>客户登录</Title>
          <Text type="secondary">登录您的账户以预订房间</Text>
        </div>

        <Form
          form={form}
          layout="vertical"
          onSubmit={handleSubmit}
          autoComplete="off"
        >
          <FormItem
            label="用户名"
            field="username"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<IconUser />}
              placeholder="请输入用户名"
              size="large"
            />
          </FormItem>

          <FormItem
            label="密码"
            field="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password
              prefix={<IconLock />}
              placeholder="请输入密码"
              size="large"
            />
          </FormItem>

          <FormItem>
            <Button type="primary" htmlType="submit" long loading={loading} size="large">
              登录
            </Button>
          </FormItem>

          <div className="flex justify-between mt-4">
            <Link href="/register" className="text-blue-600 hover:text-blue-800">
              没有账户？立即注册
            </Link>
            <Link href="/admin/login" className="text-gray-600 hover:text-gray-800">
              管理员登录
            </Link>
          </div>
        </Form>
      </Card>
    </div>
  );
}